import { defineStore } from 'pinia'
import { RouteLocationNormalized } from 'vue-router'
import { lStorage } from '@/utils/storage'

export interface TabRoute {
	path: string
	name: string
	meta: {
		hidden: boolean
		title: string
		keepAlive: boolean
		icon: string
		hasPerm: string[]
	}
}

// 默认首页路由
const Home = {
	path: '/index',
	name: 'index',
	meta: {
		hidden: false,
		title: '首页',
		keepAlive: true,
		icon: 'dashboard',
		hasPerm: ['viewHome'],
		affix: true, // 固定在标签栏
	},
}

// 静态路由列表，用于排除
const STATIC_ROUTES = ['/404', '/index']

export const useTabsStore = defineStore('tabs', {
	state: () => ({
		tabs: [Home] as Array<TabRoute>, // 存储 Tabs 数据
		activeTab: '', // 当前高亮的路由路径
	}),
	actions: {
		// 初始化 Tabs 和当前高亮路由
		initTabs() {
			const cachedTabs: TabRoute[] = [Home]
			const localTabs = lStorage.get<TabRoute[]>('WX_TABS') || []

			const uniqueTabsMap = new Map<string, TabRoute>() // 使用 Map 去重
			;[...cachedTabs, ...localTabs].forEach((tab) => {
				uniqueTabsMap.set(tab.path, tab)
			})

			this.tabs = Array.from(uniqueTabsMap.values()) // 更新状态
			this.activeTab = lStorage.get<string>('WX_ACTIVE_TAB') || '/index'
		},

		// 添加一个新 Tab
		addTab(route: RouteLocationNormalized) {
			// 如果路由在静态路由列表中或没有 meta 属性，直接返回
			if (
				STATIC_ROUTES.includes(route.path) || // 判断是否为静态路由
				!route.meta || // 判断是否有 meta 属性
				Object.keys(route.meta).length === 0 // 判断 meta 是否为空对象
			) {
				return
			}

			// 检查 Tab 是否已经存在
			if (this.tabs.some((tab) => tab.path === route.path)) {
				this.setActiveTab(route.path) // 设置为活动 Tab
				return
			}

			// 添加新 Tab
			this.tabs.push({
				path: route.path,
				name: route.name as string,
				meta: route.meta,
			})

			this.setActiveTab(route.path) // 设置为活动 Tab

			// 更新本地缓存
			lStorage.set('WX_TABS', this.tabs)
		},

		// 设置当前高亮的 Tab
		setActiveTab(path: string) {
			this.activeTab = path
			lStorage.set('WX_ACTIVE_TAB', path) // 存入本地缓存
		},

		// 移除一个 Tab
		removeTab(path: string, router) {
			console.log(path, 'path')
			// 禁止移除首页
			if (path === Home.path) {
				return
			}

			// 如果关闭的是当前 Tab，则跳转到前一个 Tab
			if (this.activeTab === path) {
				const currentIndex = this.tabs.findIndex((tab) => tab.path === path)
				const nextTab =
					this.tabs[currentIndex - 1] || this.tabs[currentIndex + 1]

				if (nextTab) {
					this.setActiveTab(nextTab.path)
					nextTick(() => {
						router.push(nextTab.path)
					})
				}
			}

			// 移除 Tab
			this.tabs = this.tabs.filter((tab) => tab.path !== path)

			// 更新本地缓存
			lStorage.set('WX_TABS', this.tabs)
		},
		clearTabs() {
			this.tabs = [Home]
			lStorage.set('WX_TABS', [Home])
			this.activeTab = ''
			lStorage.remove('WX_ACTIVE_TAB')
		},
	},
})
